import React, {FormEvent, memo, useRef, useState} from 'react';
import LoginStyle from "./LoginStyle";
import { Button, Checkbox, Form, Input,message } from 'antd';
import {getUserListByPage, loginApi} from "../../services/user";
import {useNavigate} from "react-router-dom";
import {sendSmsApi} from "../../services/sendSms";
import {UserVO} from "../../interface/UserInterface";
type Props = {};

type formObjectType={
  phone?:string,
  password?:string,
  remember?: string,
  code?:string,
};


export default memo(function Login(props: Props) {
  //路由
  const navigate = useNavigate();
  //antd全局提示
  const [messageApi, contextHolder] = message.useMessage();
  //注意,我们如果在react + ts 中使用useState函数,就需要使用到泛型
  const [formObject,setFormObject]=useState<formObjectType>({});
  //使用哪种方式进行登录
  const [isPasswordLogin,setIsPasswordLogin]=useState(true);
  //倒计时数字展示
  const [sendSmsCountdown, setSendSmsCountdown] = useState(0);
  //短信验证码
  const [smsCode,setSmsCode] = useState(0);
  //手机号码ref
  const phoneRef:any=useRef();


  function handleSubmit(event:FormEvent<HTMLFormElement>):void{
    event.preventDefault();//取消默认行为
    console.log(formObject);
  }

  /**
   * 当输入框改变时触发
   * 注意,我们使用的是受控逐渐,
   * 本质上我们只需要加入对应的dom元素和接收参数的变量即可
   * 但是由于我们使用了ts,所以在type中需要定义
   * @param event
   */
  function handleChange(event:any) {
    setFormObject({
      ...formObject,
      [event.target.name]:event.target.value,
    });
  }
  function onChangeInput(event:any) {
    console.log(event)
  }

  /** 当可以提交时触发 */
  const onFinish = (values: formObjectType) => {
    //进行判断,调用不同的接口,由于这里短信验证接口未实现,所以我们这里暂时不写
    if (isPasswordLogin){
      loginApi({phone:values.phone,password:values.password}).then((result:any)=>{
        console.log(result.data.code);
        if (result.data.code===200){
          messageApi.open({
            type:"success",
            content:result.data.msg,
            duration:1,
          }).then(()=>{
            //存储用户id和用户封面
            localStorage.setItem("yf_gaduation_zzmusic_user_id",result.data.data.userId);
            localStorage.setItem("yf_gaduation_zzmusic_user_cover",result.data.data.cover);
            localStorage.setItem("yf_gaduation_zzmusic_user_nickname",result.data.data.nickname);
            //登录成功,跳转路由
            navigate("/home");
          });
        }else{
          messageApi.open({
            type:"error",
            content:result.data.msg
          });
        }
      },(error:any)=>{
        console.log(error);
      });
    }else { //此时表示验证码登录
      /** 此时我们需要校验验证码是否正确 */
      console.log(values.code,smsCode);
      if (values.phone?.length===11){
        if (parseInt(values.code as string)===smsCode){
          /** 表示验证码通过,此时放入用户数据,进入系统 */
          getUserListByPage({pageNum:1,pageSize:1,phone:values.phone}).then((result:any)=>{
            if (result.data.code===200){
              messageApi.open({
                type:"success",
                content:"登录成功"
              });
              const userObj:UserVO=result.data.data.data[0];
              //存储用户id和用户封面
              localStorage.setItem("yf_gaduation_zzmusic_user_id",userObj.userId+"");
              localStorage.setItem("yf_gaduation_zzmusic_user_cover",userObj.cover);
              localStorage.setItem("yf_gaduation_zzmusic_user_nickname",userObj.nickname);
              //登录成功,跳转路由
              navigate("/home");
            }else {
              messageApi.open({
                type:"error",
                content:"登录失败"
              });
            }
          },(error)=>{
            console.log(error);
          });
        }else{
          messageApi.open({
            type:"error",
            content:"验证码错误"
          });
        }
      }else{
        messageApi.open({
          type:"error",
          content:"手机号码有误"
        });
      }
    }
  };
  /** 发送验证码事件 */
  function sendSmsBtn() {
    const phone:string=phoneRef.current.input.value;
    // return;
    if (phone.length===11){
      let aa = 60;
      setSendSmsCountdown(aa);
      sendSmsApi(phone).then((result:any)=>{
        console.log(result);
        if (result.data.code===200){
          messageApi.open({
            type:"success",
            content:"手机验证码发送成功"
          });
          //给变量赋值
          setSmsCode(result.data.data.code);
        }
      },(error)=>{
        console.log(error);
      });
      let timer = setInterval(() => {
        aa--;
        setSendSmsCountdown(aa);
        if (aa<1){//清除定时器
          clearInterval(timer);
        }
      }, 1000);
    }else{
      messageApi.open({
        type:"error",
        content:"手机号码有误"
      });
    }
  }


  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo);
  };

  return (
    <LoginStyle>
      {contextHolder}
      <div className="login-box">
        <div className="login-left-box"></div>

        <div className="login-right-box">
          <div className="login-form-box">
            <h1>登录</h1>
            <Form
              name="basic"
              labelCol={{ span: 7 }}
              wrapperCol={{ span: 16 }}
              style={{ maxWidth: 600 }}
              initialValues={{ remember: true }}
              onFinish={onFinish}
              onFinishFailed={onFinishFailed}
              autoComplete="off"
            >
              <Form.Item<formObjectType>
                label="手机号码"
                name="phone"
                rules={[{ required: true, message: '请输入您的手机号码' }]}
              >
                <Input ref={phoneRef} size={"large"} style={{"background":"transparent"}}/>
              </Form.Item>

              {
                isPasswordLogin
                  ?
                  <Form.Item<formObjectType>
                    label="账户密码"
                    name="password"
                    rules={[{ required: true, message: '请输入您的账户密码' }]}
                    style={{background:"#ffffff"}}
                  >
                    <Input.Password style={{background:"#ffffff"}} size={"large"}/>
                  </Form.Item>
                  :
                 <div className="code-box">
                   <Form.Item<any>
                     label="短信验证码"
                     name="code"
                     rules={[{ required: true, message: '请输入您的短信验证码' }]}
                     style={{background:"#ffffff"}}
                   >
                     <Input.Password style={{background:"#ffffff"}} size={"large"}/>
                   </Form.Item>
                   <Button disabled={sendSmsCountdown>0} onClick={sendSmsBtn}
                           className="sms-btn">
                     发送验证码 {sendSmsCountdown<1?'':`(${sendSmsCountdown})`}
                   </Button>
                 </div>
              }


              {/*<Form.Item<formObjectType>*/}
              {/*  name="remember"*/}
              {/*  valuePropName="checked"*/}
              {/*  wrapperCol={{ offset: 8, span: 16 }}*/}
              {/*>*/}
              {/*  <Checkbox>记住我</Checkbox>*/}
              {/*</Form.Item>*/}

              <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
                <Button size={"large"} className="antd-btn public-btn" type="primary" htmlType="submit">
                  登录
                </Button>
                <Button
                  onClick={()=>{setIsPasswordLogin(!isPasswordLogin)}}
                  size={"large"}
                  className="antd-btn public-btn public-background-transparent"
                >
                  {isPasswordLogin?"使用验证码登录":"使用密码登录"}
                </Button>
                <Button
                  onClick={()=>{navigate("/register")}}
                  size={"large"}
                  className="antd-btn public-btn public-background-transparent">
                  还没有账号?前往注册
                </Button>
              </Form.Item>
            </Form>
          </div>
        </div>

      </div>
    </LoginStyle>
  );
});
